﻿<?php
App::import('Core', 'CakeSession', 'i18n'); 

class AppController extends Controller {
	
	var $components = array('Acl', 'Auth', 'Session', 'Security', 'RememberMe', 'Recaptcha.Recaptcha');
	var $helpers = array('Html', 'Form', 'Session', 'Cache', 'Javascript', 'HtmlToText', 'FacebookLogin');
	
	function beforeFilter() {
               // echo $this->params['controller'].'/'.$this->params['action'];die;
		$this->disableCache();
		$this->__initAuth();
		$this->__initLayouts();
	}
	
	/**
	 * ------------------------------------------ __initAuth() ------------------------------------------
	 */
	function __initAuth() {
		$this->__authConfig();
		
		if(Configure::read('MyApp_Users.Settings.rememberMe_isActive')) {
			$this->__authRememberMeConfig();
		}
		
		$this->Session->write('MyApp_Users.InfoSettings.authCurrentUser', $this->Auth->user());
		
	}
	function __authConfig() {
		
		/**
		 * The AuthComponent uses the Security class to hash a password. The Security class uses the SHA1 scheme by default.
		 * To change another hash function used by the Auth component,
		 * use the setHash method passing it md5, sha1 or sha256 as its first and only parameter.
		 */
		Security::setHash('md5');
		
		/**
		 * Overrides the default username and password fields used for authentication.
		 * 
		 * DEFAULTS in auth.php:
		 * var $fields = array('username' => 'username', 'password' => 'password');
		 */
		//$this->Auth->fields = array('username' => 'username', 'password' => 'password');
		
		/**
		 * You can change the default login from /users/login to be any action of your choice.
		 * 
		 * DEFAULTS in auth.php:
		 * Router::normalize(array(
				'controller'=> Inflector::underscore(Inflector::pluralize($this->userModel)),
				'action' => 'login'
			))
		 */
		$this->Auth->loginAction = array('admin' => false, 'plugin' => null, 'controller' => 'users', 'action' => 'login');
				
		/**
		 * The AuthComponent remembers what controller/action pair you were trying to get to
		 * before you were asked to authenticate yourself by storing this value in the Session, under the Auth.redirect key.
		 * However, if this session value is not set (if you're coming to the login page from an external link, for example),
		 * then the user will be redirected to the URL specified in loginRedirect.
		 */
		$this->Auth->loginRedirect = array('admin' => false, 'plugin' => null, 'controller' => 'users', 'action' => 'index');
		
		/**
		 * You can also specify where you want the user to go after they are logged out,
		 * with the default being the login action.
		 */
		$systemRedirectUrl__logout = "/";
		$this->Session->write('systemRedirectUrl__logout', $systemRedirectUrl__logout);
		$this->Auth->logoutRedirect = array('admin' => false, 'plugin' => null, 'controller' => 'system_redirects', 'action' => 'system_redirect', 'logout');
		
		/**
		 * Change the default error message displayed when someone does not successfully log in.
		 * 
		 * DEFAULTS in auth.php:
		 * 'Login failed. Invalid username or password.'
		 */
		$this->Auth->loginError = __d('-app_controller', 'Невалидна комбинация име / парола. Моля, опитайте отново.', true);
		
		/**
		 * Change the default error message displayed when someone attempts to
		 * access an object or action to which they do not have access.
		 * 
		 * DEFAULTS in auth.php
		 * 'You are not authorized to access that location.'
		 */
		$this->Auth->authError = __d('-app_controller', 'Не сте ауторизирани за достъп до тази страница.', true);
		
		/**
		 * Normally, the AuthComponent will automatically redirect you as soon as it authenticates.
		 * Sometimes you want to do some more checking before you redirect users
		 * 
		 * DEFAULTS in auth.php
		 * var $autoRedirect = true;
		 */
		$this->Auth->autoRedirect = false;
		
		/**
		 * Must be set to 'actions'
		 * http://book.cakephp.org/view/248/AuthComponent-Variables#authorize-396
		 */
		$this->Auth->authorize = 'actions';
		
		/**
		 * AuthComponent needs to know about the existence of this root node, 
		 * so that when making ACL checks it can use the correct node path when looking up controllers/actions.
		 */
		$this->Auth->actionPath = 'controllers/';
	}
	function __authRememberMeConfig() {
		// again, you can customize the component settings here,
		// like this:
		// $this->RememberMe->period = '+2 months';
		// $this->RememberMe->cookieName = 'Gobshite';
		
		$cookieResult = $this->RememberMe->check();
	}
	/**
	 * -----------------------------------------/ __initAuth() ------------------------------------------
	 */
	
	/**
	 * ------------------------------------------ __initLayouts() ------------------------------------------
	 */
	function __initLayouts() {
		/*
		 * Zarejdame "control_panel" layout-a, ako e admin_*() action
		 */
		if(isset($this->params['admin'])) {
			$this->layout = 'control_panel';
		}
	}
	/**
	 * -----------------------------------------/ __initLayouts() ------------------------------------------
	 */
    
	/**
	 * ================================================= reusable functions =================================================
	 */
    function __clearAllCache() {
	    /*
		 * https://trac.cakephp.org/ticket/5807
		 */
		if(clearCache() && Cache::clear()) {
			return true;
		} else {
			return false;
		}
    }
    
    function __trimData($data) {
    	foreach ($data as $dataKey => $dataValue) {
    		if(is_string($data[$dataKey])) {
    			$data[$dataKey] = trim($data[$dataKey]);
    		}
    	}
    	
    	return $data;
    }
    
	function __startsWith($haystack, $needle) {
	    $length = strlen($needle);
	    return (substr($haystack, 0, $length) === $needle);
	}
	
	function __endsWith($haystack, $needle) {
	    $length = strlen($needle);
	    $start  = $length * -1; //negative
	    return (substr($haystack, $start) === $needle);
	}
	/**
	 * ================================================/ reusable functions =================================================
	 */
	 
	 // send the activation mail to user 
        function sendActivationLinkMail($to, $token, $username){
		/* SMTP Options */
            $this->Email->smtpOptions = array(
                 'port'=>'465',
                 'timeout'=>'30',
                 'host' => 'ssl://smtp.gmail.com',
                 'username'=>'Pankajbadukale@gmail.com',
                 'password'=>'authpay_net',
            );
            $this->Email->from = 'Pankajbadukale@gmail.com';

		$this->Email->to = $to;

		$this->Email->subject = Configure::read('MyApp_InfoSettings.projectNameForSysEmails').' - '.__d('', 'Моля, потвърдите Вашият акаунт', true).'.';

            $this->Email->sendAs = 'html';
            $hostname = SITE_WEBROOT."users/activate/".$token;
            $res = $this->Email->send("Hello ".$username."<br/> Please find the below link to activate your account.<br/><a href='".$hostname."' >Activation Link(Click Me)</a>");
            return $res;
        }
        
         // send the activation mail to user
        function sendActivationMail($to, $username){
		/* SMTP Options */
            $this->Email->smtpOptions = array(
                 'port'=>'465',
                 'timeout'=>'30',
                 'host' => 'ssl://smtp.gmail.com',
                 'username'=>'iisark@abv.bg',
                 'password'=>'######################',
            );
            $this->Email->from = 'Pankajbadukale@gmail.com';
		$this->Email->to = $to;

		$this->Email->subject = 'Welcome';

            $this->Email->sendAs = 'html';
            $res = $this->Email->send("Hello ".$username."<br/> Thanks to register with us.");
            return $res;
        }
        
       function sendMailFacebook($to, $password, $username){
            /* SMTP Options */
            $this->Email->smtpOptions = array(
                 'port'=>'465',
                 'timeout'=>'30',
                 'host' => 'ssl://smtp.gmail.com',
                 'username'=>'iisark@abv.bg',
                 'password'=>'####################',
            );
            $this->Email->from = 'Pankajbadukale@gmail.com';
            $this->Email->to = $to;
            $this->Email->subject = 'Password';
            $this->Email->sendAs = 'html';
            $res = $this->Email->send("Hello ".$username."<br/> Please find your password to login in application.<br/>".$password);
            return $res;
        }
	
}
?>